package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.domain.*;
import com.ruoyi.domain.util.SnowFlake;
import com.ruoyi.system.api.PropertyApi;
import com.ruoyi.system.mapper.CouponBillMapper;
import com.ruoyi.system.mapper.StopCarsMapper;
import com.ruoyi.system.service.IStopCarsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class StopCarsServiceImpl implements IStopCarsService {

    @Autowired
    private StopCarsMapper stopCarsMapper;
    @Autowired
    private PropertyApi propertyApi;
    @Autowired
    private SnowFlake idWorker;
    @Autowired
    private CouponBillMapper couponBillMapper;


    /**
     * @param licenseNumber
     * @param money         应付金额
     * @param licenseNumber 车牌号
     * @return
     */
    @Override
    public int stopMoney(String licenseNumber, double money, long chid) {
        Long monry = 0l; //优惠券减免金额
        Long poid = idWorker.nextId();//订单单号
        CouponBill couponBill = new CouponBill();
        for (CouponManagement couponManagement : stopCarsMapper.getCouponByCars(licenseNumber)) {
            //减少优惠券
            System.out.println(licenseNumber + "使用了" + couponManagement.getCmid() + "号优惠券");

            Map map = new HashMap<>();
            map.put("licenseNumber", licenseNumber);
            map.put("coid", couponManagement.getCmid());

            stopCarsMapper.delete(map);

            monry += couponManagement.getCouponPrice();
            if (monry>=money){
                couponBill.setOrderNum(String.valueOf(poid));
                couponBill.setCouponNum((long) (couponManagement.getCouponPrice()-(monry-money)));
                couponBill.setCouponType("支出");
                couponBill.setCmid(couponManagement.getCmid());

                couponBillMapper.insertCouponBill(couponBill);
                monry = (long) money;
                break;
            }

            //创建一个优惠券账单
            couponBill.setOrderNum(String.valueOf(poid));
            couponBill.setCouponNum(couponManagement.getCouponPrice());
            couponBill.setCouponType("支出");
            couponBill.setCmid(couponManagement.getCmid());

            couponBillMapper.insertCouponBill(couponBill);

            //添加商家优惠券记录
        }

        Long moneys = (long) (money - monry);



        //实付金额
        System.out.println("实付金额" + moneys);
        System.out.println("优惠券减免金额" + monry);
        System.out.println("应付金额" + money);
        //添加订单

        propertyApi.add(new PayOrder(poid, "200", 0l, 0l, stopCarsMapper.getpmidBychid(chid), 1l, 1l, (long) money, 1l, 4l));

        //添加流水

        propertyApi.add(new PayWater("200", 0l, 0l, poid, moneys, 0));



        return 200;
    }
}
